package com.xavier.dong.nacos.grpc.server.grpc;


import com.alibaba.fastjson2.JSON;
import com.google.protobuf.TextFormat;
import com.xavier.dong.nacos.grpc.api.HelloStreamGrpc;
import com.xavier.dong.nacos.grpc.api.Simple;
import com.xavier.dong.nacos.grpc.api.SimpleList;
import com.xavier.dong.nacos.grpc.api.SimpleSummary;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Example grpc server service implementation class.
 */
@GrpcService
@Slf4j
public class GrpcServerService extends HelloStreamGrpc.HelloStreamImplBase {


    /**
     * A Unary RPC.
     * <p>
     * 请求一个 Requset 对象，响应一个 Response 对象
     *
     * @param request          请求
     * @param responseObserver 响应观察者
     */
    @Override
    //@Secured("ROLE_GREET")  // 权限认证
    public void simpleRpc(com.xavier.dong.nacos.grpc.api.Simple request, StreamObserver<com.xavier.dong.nacos.grpc.api.SimpleFeature> responseObserver) {
        com.xavier.dong.nacos.grpc.api.SimpleFeature simpleFeature = com.xavier.dong.nacos.grpc.api.SimpleFeature.newBuilder()
                .setName(String.format("Hello, %s. This message comes from gRPC.", request.getName()))
                .build();
        // 解决中文打印 乱码问题
        log.info("msg: {}", TextFormat.printer().escapingNonAscii(false).printToString(simpleFeature));
        responseObserver.onNext(simpleFeature);
        responseObserver.onCompleted();
    }


    /**
     * A server-to-client streaming RPC.
     * <p>
     * 请求一个 Requset 对象，响应一个 Stream 对象
     *
     * @param request          请求
     * @param responseObserver 响应观察者
     */
    @Override
    //@Secured("ROLE_GREET")  // 权限认证
    public void server2ClientRpc(SimpleList request, StreamObserver<com.xavier.dong.nacos.grpc.api.SimpleFeature> responseObserver) {
        final List<Simple> simpleListList = request.getSimpleListList();
        final String names = simpleListList.stream().map(Simple::getName).collect(Collectors.joining("-"));
        com.xavier.dong.nacos.grpc.api.SimpleFeature simpleFeature = com.xavier.dong.nacos.grpc.api.SimpleFeature.newBuilder()
                .setName(String.format("Hello, %s. This message comes from gRPC.", names))
                .build();
        //log.info("request msg: {}", TextFormat.printer().escapingNonAscii(false).printToString());
        // 解决中文打印 乱码问题
        log.info("response msg: {}", TextFormat.printer().escapingNonAscii(false).printToString(simpleFeature));
        responseObserver.onNext(simpleFeature);
        responseObserver.onCompleted();

    }


    /**
     * A client-to-server streaming RPC.
     * <p>
     * 请求一个 Stream 对象，响应一个 Response 对象
     *
     * @param responseObserver 响应观察者
     * @return {@link StreamObserver}<{@link Simple}>
     */
    @Override
    //@Secured("ROLE_GREET")  // 权限认证
    public StreamObserver<com.xavier.dong.nacos.grpc.api.Simple> client2ServerRpc(StreamObserver<SimpleSummary> responseObserver) {

        return new StreamObserver<com.xavier.dong.nacos.grpc.api.Simple>() {
            @Override
            public void onNext(Simple simple) {
                com.xavier.dong.nacos.grpc.api.SimpleFeature simpleFeature = com.xavier.dong.nacos.grpc.api.SimpleFeature.newBuilder()
                        .setName(String.format("Hello, %s. This message comes from gRPC.", simple.getName()))
                        .build();
                log.info("msg: {}", JSON.toJSONString(simple.getName()));
            }

            @Override
            public void onError(Throwable throwable) {
                log.error("client2ServerRpc error : {}", Status.fromThrowable(throwable));
            }

            @Override
            public void onCompleted() {
                responseObserver.onNext(SimpleSummary.newBuilder().setFeatureCount(100000).build());
                responseObserver.onCompleted();
            }
        };
    }

    /**
     * A Bidirectional streaming RPC.
     * <p>
     * rpc 请求一个 Stream，响应一个 Stream 对象
     *
     * @param responseObserver 响应观察者
     * @return {@link StreamObserver}<{@link Simple}>
     */
    @Override
    //@Secured("ROLE_GREET")  // 权限认证
    public StreamObserver<com.xavier.dong.nacos.grpc.api.Simple> bindirectionalStreamRpc(StreamObserver<com.xavier.dong.nacos.grpc.api.Simple> responseObserver) {
        return new StreamObserver<com.xavier.dong.nacos.grpc.api.Simple>() {
            @Override
            public void onNext(Simple simple) {
                com.xavier.dong.nacos.grpc.api.SimpleFeature simpleFeature = com.xavier.dong.nacos.grpc.api.SimpleFeature.newBuilder()
                        .setName(String.format("Hello, %s. This message comes from gRPC.", simple.getName()))
                        .build();
                log.info("msg: {}", JSON.toJSONString(simple.getName()));
            }

            @Override
            public void onError(Throwable throwable) {
                log.error("bindirectionalStreamRpc error : {}", Status.fromThrowable(throwable));
            }

            @Override
            public void onCompleted() {
                responseObserver.onNext(com.xavier.dong.nacos.grpc.api.Simple.newBuilder().setName("fdsfsdafadsfdasfdasfadsfasdfasdfadsfdasfasdfas").build());
                responseObserver.onCompleted();
            }
        };
    }
}